package com.zone.service.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import com.alibaba.nacos.common.packagescan.resource.Resource;
import com.zone.common.security.utils.SecurityUtils;
import com.zone.service.domain.dto.PdaPwdDto;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import com.zone.common.log.annotation.Log;
import com.zone.common.log.enums.BusinessType;
import com.zone.common.security.annotation.RequiresPermissions;
import com.zone.service.domain.Employees;
import com.zone.service.service.IEmployeesService;
import com.zone.common.core.web.controller.BaseController;
import com.zone.common.core.web.domain.AjaxResult;
import com.zone.common.core.utils.poi.ExcelUtil;
import com.zone.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 人员管理Controller
 * 
 * @author liuyang
 * @date 2025-10-21
 */
@RestController
@RequestMapping("/employees")
public class EmployeesController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(EmployeesController.class);
    
    @Autowired
    private IEmployeesService employeesService;

    /**
     * 查询人员管理列表
     */
    @RequiresPermissions("service:employees:list")
    @GetMapping("/list")
    public TableDataInfo list(Employees employees)
    {
        startPage();
        List<Employees> list = employeesService.selectEmployeesList(employees);
        return getDataTable(list);
    }

    /**
     * 导出人员管理列表
     */
    @RequiresPermissions("service:employees:export")
    @Log(title = "人员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Employees employees)
    {
        List<Employees> list = employeesService.selectEmployeesList(employees);
        ExcelUtil<Employees> util = new ExcelUtil<Employees>(Employees.class);
        util.exportExcel(response, list, "人员管理数据");
    }

    /**
     * 获取人员管理详细信息
     */
    @RequiresPermissions("service:employees:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(employeesService.selectEmployeesById(id));
    }

    /**
     * 新增人员管理
     */
    @RequiresPermissions("service:employees:add")
    @Log(title = "人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Employees employees)
    {
        if (!employeesService.checkEmployeeNoUnique(employees))
        {
            return error("新增员工'" + employees.getEmpNo() + "'失败，员工号已存在");
        }
        // 设置pda初始密码为员工工号，加密
        employees.setPdaPwd(SecurityUtils.encryptPassword(employees.getEmpNo()));
        // 设置创建人
        employees.setCreateBy(SecurityUtils.getUsername());
        return toAjax(employeesService.insertEmployees(employees));
    }

    /**
     * 修改人员管理
     */
    @RequiresPermissions("service:employees:edit")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Employees employees)
    {
        // 设置更新人
        employees.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(employeesService.updateEmployees(employees));
    }

    /**
     * 删除人员管理
     */
    @RequiresPermissions("service:employees:remove")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(employeesService.deleteEmployeesByIds(ids));
    }

    /**
     * 修改pad密码
     */
    @RequiresPermissions("service:employees:edit")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changePadPwd")
    public AjaxResult changePadPwd(@RequestBody PdaPwdDto pdaPwdDto)
    {
        if (pdaPwdDto.getId() == null) {
            return error("请选择人员");
        }
        // 根据id查询人员信息
        Employees employees = employeesService.selectEmployeesById(pdaPwdDto.getId());
        if (employees == null) {
            return error("员工不存在");
        }
        // 获取人员的pad密码并解密
        String pdaPwd = SecurityUtils.encryptPassword(pdaPwdDto.getOldPassword());
        // 将加密后的密码和pdaPwdDto的oldPdaPwd比较
        if (!SecurityUtils.matchesPassword(pdaPwdDto.getOldPassword(), employees.getPdaPwd())) {
            return error("原密码错误");
        }
        // 判断新密码是否与原密码相同
        if (pdaPwdDto.getNewPassword().equals(pdaPwdDto.getOldPassword())) {
            return error("新密码不能与原密码相同");
        }
        // 将新密码进行加密, 然后将加密后的密码保存到employees中
        employees.setPdaPwd(SecurityUtils.encryptPassword(pdaPwdDto.getNewPassword()));

        return toAjax(employeesService.updateEmployees( employees));
    }

    /**
     * 重置pad密码
     */
    @RequiresPermissions("service:employees:edit")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPadPwd/{id}")
    public AjaxResult resetPadPwd(@PathVariable Long id) {
        if (id == null) {
            return error("请选择人员");
        }
        Employees employees = employeesService.selectEmployeesById(id);
        if (employees == null) {
            return error("员工不存在");
        }
        try {
            employees.setPdaPwd(SecurityUtils.encryptPassword(employees.getEmpNo()));
            return toAjax(employeesService.updateEmployees(employees));
        } catch (Exception e) {
            return error("重置密码失败: " + e.getMessage());
        }
    }
    /**
     * 导出人员模板
     */
    @RequiresPermissions("service:employees:export")
    @Log(title = "人员管理", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        String templatePath = "templates/cleaningcreaw.xls"; // 👈 确认拼写！应为 cleaningcrew？

        ClassPathResource resource = new ClassPathResource(templatePath);
        if (!resource.exists()) {
            logger.error("模板文件不存在: {}", templatePath);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        try {
            // 设置正确的 Content-Type 和编码
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");

            // 安全编码文件名
            String fileName = URLEncoder.encode("人员导入模板.xls", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 流式拷贝（Spring 提供工具类更简洁）
            StreamUtils.copy(resource.getInputStream(), response.getOutputStream());
            response.flushBuffer();

        } catch (IOException e) {
            logger.error("模板下载异常", e);
            try {
                response.reset();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件下载失败");
            } catch (IOException ignored) {}
        }
    }
    
    /**
     * 导入人员数据
     */
    @RequiresPermissions("service:employees:add")
    @Log(title = "人员管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult execlImport(MultipartFile file, boolean updateSupport) {
        try {
            logger.info("开始导入人员数据");
            
            if (file == null || file.isEmpty()) {
                logger.warn("上传文件为空");
                return AjaxResult.error("上传文件不能为空");
            }
            
            logger.info("文件名: {}, 文件大小: {}", file.getOriginalFilename(),file.getSize());
            
            // 创建ExcelUtil实例
            ExcelUtil<Employees> util = new ExcelUtil<Employees>(Employees.class);
            
            // 解析Excel文件
            List<Employees> employeesList = util.importExcel(file.getInputStream());
            
            // 添加调试信息
            logger.info("解析后的数据条数: {}", employeesList != null ? employeesList.size() : "null");
            
            if (employeesList == null) {
                logger.warn("解析后的数据为null");
                return AjaxResult.error("导入数据解析失败，请检查Excel文件格式");
            }
            
            if (employeesList.isEmpty()) {
                logger.warn("解析后的数据为空列表");
                return AjaxResult.error("导入数据为空，请检查Excel文件是否包含数据");
            }
            // 循环设置pda密码
            for (Employees employees : employeesList) {
                if (employees.getPdaPwd() == null) {
                    employees.setPdaPwd(SecurityUtils.encryptPassword(employees.getEmpNo()));
                }
                if (employees.getIsRouteLeader() == null) {
                    employees.setIsRouteLeader("N");
                }
                if (employees.getBusinessType() == null) {
                    employees.setBusinessType(0L);
                }
                if (employees.getEmploymentStatus() == null) {
                    employees.setEmploymentStatus(0);
                }
                // 设置逻辑删除未0
                if (employees.getDeleted() == null) {
                    employees.setDeleted(0L);
                }
                // 设置创建人
                employees.setCreateBy(SecurityUtils.getUsername());
            }
            return toAjax(employeesService.batchInsertEmployees(employeesList));
        } catch (Exception e) {
            logger.error("导入人员数据失败: ", e);
            if (e.getMessage().contains("员工工号已存在")) {
                return AjaxResult.error("导入失败：员工工号已存在");
            }
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
}

